package com.chen.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chen.blog.dao.mapper.TagMapper;
import com.chen.blog.dao.pojo.Article;
import com.chen.blog.dao.pojo.Tag;
import com.chen.blog.service.TagService;
import com.chen.blog.vo.ArticleVo;
import com.chen.blog.vo.Result;
import com.chen.blog.vo.TagVo;
import org.apache.commons.collections.CollectionUtils;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class TagServiceImpl implements TagService {

    @Autowired
    private TagMapper tagMapper;

    private TagVo copy(Tag tag){
        TagVo tagVo = new TagVo();
        //BeanUtils.copyProperties("转换前的类a", "转换后的类b");
        //复制属性，并且属性名字要相同，a 类属性要多于b类
        //此处tag_name赋值不成功，因为驼峰命名的问题

        BeanUtils.copyProperties(tag,tagVo);
        tagVo.setId(String.valueOf(tag.getId()));
//        tagVo.setTag_name(tag.getTagName());
//        System.out.println("tag的名字"+tag.getTagName());
//        System.out.println("tagvo的名字"+tagVo.getTag_name());
//        tagVo.setId(tag.getId());
        return tagVo;
    }

    private List<TagVo> copyList(List<Tag> tagList) {
        List<TagVo> tagVoList = new ArrayList<>();
        for (Tag tag : tagList){
            tagVoList.add(copy(tag));
        }
        return tagVoList;
    }

    @Override
    public List<TagVo> findTagsByArticleId(Long id) {

        //mybatisplus无法进行多表查询
        List<Tag> tags = tagMapper.findTagsByArticleId(id);
        return copyList(tags);
    }

    @Override
    public Result hots(int limit) {
        /**
         * 1.标签拥有的文章数量最多 最热标签
         * 2.查询 根据tag_id 分组 计数，从大到小 排列 取前limit个
         */
        List<Long> tagIds = tagMapper.findHotsTagIds(limit);
        //判断tagIds是否为空
        if (CollectionUtils.isEmpty(tagIds)){
            return Result.success(Collections.emptyList());
        }
        //需要的是tagId 和tagName  tag对象
        List<Tag> tagList=tagMapper.findTagsByTagIds(tagIds);
        return Result.success(tagList);
    }

    @Override
    public Result findAll() {
        LambdaQueryWrapper<Tag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Tag::getId,Tag::getTagName);
        List<Tag> tags = tagMapper.selectList(queryWrapper);

        return Result.success(copyList(tags));
    }

    @Override
    public Result findAllDetail() {
        List<Tag> tags = tagMapper.selectList(new LambdaQueryWrapper<>());
        return Result.success(copyList(tags));
    }

    @Override
    public Result findAllDetailDetail(Long id) {
        Tag tag = tagMapper.selectById(id);
        return Result.success(copy(tag));

    }
}
